<template>
    <div class="publish-notification-container">
        <!-- 顶部导航栏 -->
        <header class="header">
            <button class="back-btn" @click="goBack">
                <span class="back-icon">‹</span>
                发布通知
            </button>
        </header>

        <!-- 主要内容 -->
        <main class="main-content">
            <!-- 队伍名称 -->
            <div class="team-name-section">
                <h2 class="team-name">{{ teamName }}</h2>
            </div>

            <!-- 发布表单 -->
            <div class="publish-form">
                <!-- 通知标题 -->
                <div class="form-group">
                    <label class="form-label">通知标题</label>
                    <input 
                        v-model="formData.title" 
                        type="text" 
                        class="form-input"
                        placeholder="请输入通知标题..."
                        maxlength="100"
                    />
                    <div class="char-count">{{ formData.title.length }}/100</div>
                </div>

                <!-- 通知内容 -->
                <div class="form-group">
                    <label class="form-label">通知内容</label>
                    <textarea 
                        v-model="formData.content" 
                        class="form-textarea"
                        placeholder="请输入通知内容..."
                        rows="6"
                        maxlength="1000"
                    ></textarea>
                    <div class="char-count">{{ formData.content.length }}/1000</div>
                </div>

                <!-- 相关链接 -->
                <div class="form-group">
                    <label class="form-label">相关链接（可选）</label>
                    <input
                        v-model="formData.link"
                        type="url"
                        class="form-input"
                        placeholder="请输入相关链接..."
                    />
                </div>

                <!-- 通知设置 -->
                <div class="form-group">
                    <label class="form-label">通知设置</label>
                    <div class="checkbox-group">
                        <label class="checkbox-item">
                            <input
                                v-model="formData.requireConfirmation"
                                type="checkbox"
                                class="checkbox-input"
                            />
                            <span class="checkbox-text">需要成员确认此通知</span>
                            <span class="checkbox-hint">勾选后，成员需要确认已阅读此通知</span>
                        </label>
                    </div>
                </div>

                <!-- 上传图片 -->
                <div class="form-group">
                    <label class="form-label">上传图片</label>
                    
                    <!-- 图片预览 -->
                    <div v-if="uploadedImages.length > 0" class="uploaded-images">
                        <div 
                            v-for="(image, index) in uploadedImages" 
                            :key="index"
                            class="image-item"
                        >
                            <img :src="image.url" :alt="`图片${index + 1}`" class="preview-image" />
                            <button 
                                class="remove-image-btn" 
                                @click="removeImage(index)"
                                type="button"
                            >
                                ×
                            </button>
                        </div>
                    </div>

                    <!-- 上传按钮 -->
                    <div class="upload-section">
                        <input 
                            ref="fileInput"
                            type="file" 
                            accept="image/*" 
                            multiple
                            @change="handleFileSelect"
                            class="file-input"
                        />
                        <button 
                            type="button"
                            class="upload-btn"
                            @click="triggerFileSelect"
                            :disabled="uploading || uploadedImages.length >= 9"
                        >
                            <span v-if="uploading">上传中...</span>
                            <span v-else>{{ uploadedImages.length >= 9 ? '最多9张图片' : '选择图片' }}</span>
                        </button>
                        <div class="upload-tip">支持JPG、PNG格式，最多9张图片</div>
                    </div>
                </div>
            </div>

            <!-- 发布按钮 -->
            <div class="publish-section">
                <button 
                    type="button" 
                    class="publish-btn" 
                    @click="publishNotification"
                    :disabled="!canPublish || publishing"
                >
                    {{ publishing ? '发布中...' : '发布通知' }}
                </button>
            </div>
        </main>

        <!-- 成功提示 -->
        <div v-if="successMessage" class="success-toast">
            <div class="success-icon">✅</div>
            <p class="success-text">{{ successMessage }}</p>
        </div>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-toast">
            <div class="error-icon">❌</div>
            <p class="error-text">{{ errorMessage }}</p>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { publishNotificationService, uploadImageService } from '@/api/notification.js'
import { getTeamDetailService } from '@/api/team.js'

const router = useRouter()
const route = useRoute()

// 响应式数据
const teamName = ref('')
const uploading = ref(false)
const publishing = ref(false)
const uploadedImages = ref([])
const successMessage = ref('')
const errorMessage = ref('')

// 表单数据
const formData = ref({
    title: '',
    content: '',
    link: '',
    requireConfirmation: false
})

// 文件输入引用
const fileInput = ref(null)

// 计算属性
const teamId = computed(() => route.params.teamId)

const canPublish = computed(() => {
    return formData.value.title.trim() && formData.value.content.trim()
})

// 页面挂载时初始化
onMounted(async () => {
    await fetchTeamInfo()
})

// 获取队伍信息
const fetchTeamInfo = async () => {
    try {
        const response = await getTeamDetailService(teamId.value)
        if (response.code === 200 && response.data) {
            teamName.value = response.data.teamName + '队'
        } 
        console.log('获取队伍信息成功，队伍ID:', teamId.value, '队伍名称:', teamName.value)
    } catch (error) {
        console.error('获取队伍信息失败:', error)
    
    }
}

// 触发文件选择
const triggerFileSelect = () => {
    fileInput.value?.click()
}

// 处理文件选择
const handleFileSelect = async (event) => {
    const files = Array.from(event.target.files)
    if (files.length === 0) return

    // 检查文件数量限制
    if (uploadedImages.value.length + files.length > 9) {
        showError('最多只能上传9张图片')
        return
    }

    // 检查文件类型和大小
    const validFiles = files.filter(file => {
        if (!file.type.startsWith('image/')) {
            showError(`${file.name} 不是有效的图片文件`)
            return false
        }
        if (file.size > 5 * 1024 * 1024) { // 5MB
            showError(`${file.name} 文件大小超过5MB`)
            return false
        }
        return true
    })

    if (validFiles.length === 0) return

    // 上传文件
    uploading.value = true
    try {
        for (const file of validFiles) {
            const formData = new FormData()
            formData.append('file', file) // 注意：后端接口参数名是 'file'

            const response = await uploadImageService(formData)
            if (response.code === 200 && response.data) {
                uploadedImages.value.push({
                    url: response.data.url || response.data.fileUrl, // 适配不同的返回字段名
                    name: file.name
                })
                console.log(`${file.name} 上传成功`)
            } else {
                showError(`${file.name} 上传失败: ${response.message}`)
            }
        }
    } catch (error) {
        console.error('上传图片失败:', error)
        showError('上传图片失败，请稍后重试')
    } finally {
        uploading.value = false
        // 清空文件输入
        if (fileInput.value) {
            fileInput.value.value = ''
        }
    }
}

// 移除图片
const removeImage = (index) => {
    uploadedImages.value.splice(index, 1)
}

// 发布通知
const publishNotification = async () => {
    if (!canPublish.value || publishing.value) return

    publishing.value = true
    try {
        const notificationData = {
            teamId: teamId.value,
            title: formData.value.title.trim(),
            content: formData.value.content.trim(),
            link: formData.value.link.trim() || null,
            images: uploadedImages.value.map(img => ({ url: img.url })),
            requireConfirmation: formData.value.requireConfirmation
        }

        console.log('发布通知数据:', notificationData)
        const response = await publishNotificationService(notificationData)

        if (response.code === 200) {
            showSuccess('通知发布成功！')
            setTimeout(() => {
                router.go(-1) // 返回通知中心
            }, 1500)
        } else {
            showError(response.message || '发布失败，请稍后重试')
        }
    } catch (error) {
        console.error('发布通知失败:', error)
        showError('发布失败，请稍后重试')
    } finally {
        publishing.value = false
    }
}

// 显示成功提示
const showSuccess = (message) => {
    errorMessage.value = ''
    successMessage.value = message
    setTimeout(() => {
        successMessage.value = ''
    }, 3000)
}

// 显示错误提示
const showError = (message) => {
    successMessage.value = ''
    errorMessage.value = message
    setTimeout(() => {
        errorMessage.value = ''
    }, 3000)
}

// 返回上一页
const goBack = () => {
    router.go(-1)
}
</script>

<style scoped lang="scss">
//@import '@/assets/css/publish-notification.css';
.publish-notification-container {
    min-height: 100vh;
    background: #f5f5f5;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 顶部导航栏 */
.header {
    background: #FF8C00;
    padding: 12px 16px;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.back-btn {
    background: none;
    border: none;
    color: white;
    font-size: 18px;
    font-weight: 500;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
}

.back-icon {
    font-size: 24px;
    font-weight: bold;
}

/* 主要内容 */
.main-content {
    background: white;
    min-height: calc(100vh - 60px);
}

/* 队伍名称区域 */
.team-name-section {
    padding: 20px 16px;
    border-bottom: 1px solid #e5e5e5;
}

.team-name {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

/* 发布表单 */
.publish-form {
    padding: 16px;
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
}

.form-input {
    width: 100%;
    padding: 12px;
    border: 1px solid #e5e5e5;
    border-radius: 6px;
    font-size: 16px;
    transition: border-color 0.3s ease;
    box-sizing: border-box;
}

.form-input:focus {
    outline: none;
    border-color: #FF8C00;
}

.form-textarea {
    width: 100%;
    padding: 12px;
    border: 1px solid #e5e5e5;
    border-radius: 6px;
    font-size: 16px;
    line-height: 1.5;
    resize: vertical;
    min-height: 120px;
    transition: border-color 0.3s ease;
    box-sizing: border-box;
    font-family: inherit;
}

.form-textarea:focus {
    outline: none;
    border-color: #FF8C00;
}

.char-count {
    text-align: right;
    font-size: 12px;
    color: #999;
    margin-top: 4px;
}

/* 复选框样式 */
.checkbox-group {
    margin-top: 8px;
}

.checkbox-item {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    cursor: pointer;
    padding: 8px;
    border-radius: 6px;
    transition: background-color 0.2s ease;
}

.checkbox-item:hover {
    background: #f8f9fa;
}

.checkbox-input {
    margin: 0;
    width: 16px;
    height: 16px;
    cursor: pointer;
    flex-shrink: 0;
    margin-top: 2px;
}

.checkbox-text {
    font-size: 14px;
    color: #333;
    font-weight: 500;
    line-height: 1.4;
}

.checkbox-hint {
    font-size: 12px;
    color: #666;
    margin-top: 2px;
    line-height: 1.3;
}

/* 图片上传 */
.uploaded-images {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 12px;
    margin-bottom: 16px;
}

.image-item {
    position: relative;
    border-radius: 6px;
    overflow: hidden;
    aspect-ratio: 1;
}

.preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
}

.remove-image-btn {
    position: absolute;
    top: 4px;
    right: 4px;
    background: rgba(0, 0, 0, 0.6);
    color: white;
    border: none;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    transition: background-color 0.3s ease;
}

.remove-image-btn:hover {
    background: rgba(0, 0, 0, 0.8);
}

.upload-section {
    text-align: center;
    padding: 20px;
    border: 2px dashed #e5e5e5;
    border-radius: 6px;
    transition: border-color 0.3s ease;
}

.upload-section:hover {
    border-color: #FF8C00;
}

.file-input {
    display: none;
}

.upload-btn {
    background: #FF8C00;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 6px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 8px;
}

.upload-btn:hover:not(:disabled) {
    background: #e67e00;
}

.upload-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.upload-tip {
    font-size: 12px;
    color: #999;
}

/* 发布按钮区域 */
.publish-section {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background: white;
    border-top: 1px solid #e5e5e5;
}

.publish-btn {
    width: 100%;
    background: #007bff;
    color: white;
    border: none;
    padding: 14px;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.publish-btn:hover:not(:disabled) {
    background: #0056b3;
}

.publish-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
}

/* 提示信息 */
.success-toast,
.error-toast {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 16px 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    z-index: 1000;
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 500;
    animation: popIn 0.3s ease-out;
    min-width: 200px;
    justify-content: center;
}

.success-toast {
    background: #28a745;
    color: white;
}

.error-toast {
    background: #dc3545;
    color: white;
}

@keyframes popIn {
    0% {
        opacity: 0;
        transform: translate(-50%, -50%) scale(0.8);
    }
    100% {
        opacity: 1;
        transform: translate(-50%, -50%) scale(1);
    }
}

.success-icon,
.error-icon {
    font-size: 18px;
    margin: 0;
}

.success-text,
.error-text {
    font-size: 14px;
    font-weight: 500;
    margin: 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .publish-form {
        padding-bottom: 80px; /* 为底部按钮留出空间 */
    }

    .uploaded-images {
        grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
        gap: 8px;
    }

    .form-input,
    .form-textarea {
        font-size: 16px; /* 防止iOS缩放 */
    }
}
</style>